﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Nhandang
{
    public class Network
    {
        public int _hiddenDims;
        public int _inputDims;
        public Layer _hidden;
        public Layer _inputs;
        public Neuron _output;            // Output neuron.

        public Network(int input, int hidden)
        {
            _inputDims = input;
            _hiddenDims = hidden;
          //  Initialise(Application.StartupPath + "\\hiddenW.ann", Application.StartupPath + "\\outputW.ann");
        }
        public double Test(string values)
        {
            {
                return Activate(new Pattern(values, _inputDims));
                // return 0.001;
            }
        }
        ////////////////////////////////////////////////////////////////////
        // Dau vao la vector dac trung
        // Tra ve dau ra (output) cua mang neuron
        ////////////////////////////////////////////////////////////////////
        private double Activate(Pattern pattern)
        {
            for (int i = 0; i < pattern.Inputs.Length; i++)
            {
                _inputs[i].Output = pattern.Inputs[i];
            }
            foreach (Neuron neuron in _hidden)
            {
                neuron.Activate();
            }
            _output.Activate();
            return _output.Output;
        }
        ////////////////////////////////////////////////////////////////////
        // Dau vao la 1 dong trong file trong so cua neuron
        // Ham nay luu cac trong so vao mang 1 chieu
        ////////////////////////////////////////////////////////////////////
        private double[] GetWeights(string line)
        {
            string[] arrW;
            arrW = line.Split(',');
            double[] arrWvalue = new double[arrW.Length];
            for (int i = 0; i < arrW.Length; i++)
                arrWvalue[i] = Convert.ToDouble(arrW[i].Trim());
            return arrWvalue;
        }
        ////////////////////////////////////////////////////////////////////
        // Khoi tao mang neuron voi cac trong so load tu file
        ////////////////////////////////////////////////////////////////////
        public void Initialise(string hiddenWsfile, string outputWfile)
        {
            string strOutputW;
            _inputs = new Layer(_inputDims);
            _hidden = new Layer(_hiddenDims, _inputs, hiddenWsfile);
            // Neuron Output
            using (StreamReader reader = new StreamReader(outputWfile))
            {
                strOutputW = reader.ReadLine();
            }
            double[] arrWvalue = GetWeights(strOutputW);
            _output = new Neuron(_hidden, arrWvalue);
        }
    }
}
